package org.skydiveapp2;

import java.util.ArrayList;

import org.skydiveapp2.ui.InterfaceManager;
import org.skydiveapp2.ui.LogEntryListCursorAdapter;
import org.skydiveapplibrary.repository.LogEntryRepository;
import org.skydiveapplibrary.ui.NumberDialog;
import org.skydiveapplibrary.ui.NumberDialog.OnNumberSetListener;

import android.app.Activity;
import android.app.ListFragment;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;

public class LogEntryListFragment extends ListFragment
{	
	onLogEntryEditRequestListener mListener;

	public interface onLogEntryEditRequestListener {
        public void onLogEntryEditRequest(Bundle args);
    }
	
	// repository
	private LogEntryRepository repository;
	private Cursor cursor;
	
	// data
	private boolean isDualDisplay;

	// listeners
	private OnClickListener addListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			addLogEntry();
		}
	};
	
	private OnClickListener copyListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			addNewFromPrevious();
		}
	};
	
	private OnClickListener signListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			signEntries();
		}
	};
	
	private OnClickListener goToListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			goToEntry();
		}
	};
	
	// goto number listener
	private OnNumberSetListener goToSetListener = new OnNumberSetListener()
	{
		@Override
		public void onNumberSet(NumberDialog dialog, int number)
		{
			int position = 0;
			try
			{
				cursor.moveToFirst();
				while (cursor.moveToNext())
				{
					if (cursor.getInt(1) == number)
					{
						position = cursor.getPosition();
					}
				}
			}
			finally
			{
				
			}
			getListView().setSelection(position);
		}
	}; 
	
	private OnClickListener cancelListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			toggleSignMode();
		}
	};
	
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Check that the container activity has implemented the callback interface
        try {
            mListener = (onLogEntryEditRequestListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() 
                    + " must implement OnItemSelectedListener");
        }
    }
		
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		repository = new LogEntryRepository(getActivity());
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    		Bundle savedInstanceState)
	{	
		View logEntryLeftFrame = getActivity().findViewById(R.id.leftFrame);
		isDualDisplay = logEntryLeftFrame != null;
		
		// Inflate the layout for this fragment
	    View view =  inflater.inflate(R.layout.log_entry_list_view, container, false);
	    
	    // set adapter
    	cursor = repository.getLogEntryCursor();
    	getActivity().startManagingCursor(cursor);
		setListAdapter(new LogEntryListCursorAdapter(getActivity(), cursor));
	    
		// init ui
		if (isDualDisplay)
		{
			initializeTabletUI(view);
		}
		else
		{
			initializePhoneUI(view);
		}
		
		return view;
	}
    
   
    public void onResume()
    {
    	super.onResume();

    	getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }
	
    @Override
	public void onListItemClick(ListView lv, View view, int position, long id)
    {
    	if (((LogEntryListCursorAdapter) getListAdapter()).multiSelect)
    	{
	       	// update selection
	       	((LogEntryListCursorAdapter)getListAdapter()).toggleSelection((int)id);
    	}
    	else
    	{
    		Bundle args = new Bundle();
    		args.putInt(Constants.EXTRA_LOG_ENTRY_ID, (int)id);
    		
    		mListener.onLogEntryEditRequest(args);
    	}
    }
    
	private void initializePhoneUI(View view)
	{
		setHasOptionsMenu(true);
	}
    
	private void initializeTabletUI(View view)
	{	
		// add button click listeners
		ImageButton addButton = (ImageButton) view.findViewById(R.id.LogEntryListAddButton);
		addButton.setOnClickListener(addListener);
		
		ImageButton gotoButton = (ImageButton) view.findViewById(R.id.LogEntryListGoToButton);
		gotoButton.setOnClickListener(goToListener);
		
		ImageButton copyButton = (ImageButton) view.findViewById(R.id.LogEntryListCopyButton);
		copyButton.setOnClickListener(copyListener);
		
		ImageButton signButton = (ImageButton) view.findViewById(R.id.LogEntryListSignButton);
		signButton.setOnClickListener(signListener);
		
		ImageButton cancelButton = (ImageButton) view.findViewById(R.id.LogEntryListCancelButton);
		cancelButton.setOnClickListener(cancelListener);
	}
	
	public void refreshListView()
	{
		((LogEntryListCursorAdapter) getListAdapter()).clearSelection();
		cursor.requery();
	}
	
	public void toggleSignMode()
	{
		if (((LogEntryListCursorAdapter) getListAdapter()).multiSelect)
		{
			getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			((LogEntryListCursorAdapter) getListAdapter()).multiSelect = false;
			((LogEntryListCursorAdapter) getListAdapter()).clearSelection();
			refreshListView();
			
			if (isDualDisplay)
			{
				InterfaceManager.getInstance().setSubtitleText(getActivity(), R.string.log_book_label);
				setButtonVisibility(R.id.LogEntryListCancelButton, View.GONE);
				setButtonVisibility(R.id.LogEntryListAddButton, View.VISIBLE);
				setButtonVisibility(R.id.LogEntryListCopyButton, View.VISIBLE);
				setButtonVisibility(R.id.LogEntryListGoToButton, View.VISIBLE);
			}
			else
			{
				getActivity().invalidateOptionsMenu();
			}
		}
		else
		{
			getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			((LogEntryListCursorAdapter) getListAdapter()).multiSelect = true;
			refreshListView();
			
			if (isDualDisplay)
			{
				InterfaceManager.getInstance().setSubtitleText(getActivity(), R.string.log_entry_list_select_label);
			
				setButtonVisibility(R.id.LogEntryListCancelButton, View.VISIBLE);
				setButtonVisibility(R.id.LogEntryListAddButton, View.GONE);
				setButtonVisibility(R.id.LogEntryListCopyButton, View.GONE);
				setButtonVisibility(R.id.LogEntryListGoToButton, View.GONE);
			}
			else
			{
				getActivity().invalidateOptionsMenu();
			}
		}
	}
	
	private void setButtonVisibility(int id, int visibility)
	{
		ImageButton imageButton = (ImageButton) getView().findViewById(id);
		imageButton.setVisibility(visibility);
	}
	
	public void highlightRow(int rowId)
	{
		((LogEntryListCursorAdapter)getListAdapter()).toggleSelection(rowId);
		cursor.requery();
	}
	
    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        toggleSignMode();
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    	inflater.inflate(R.menu.menu_add, menu);
    	inflater.inflate(R.menu.menu_copy, menu);
    	inflater.inflate(R.menu.menu_sign, menu);
    	inflater.inflate(R.menu.menu_goto, menu);
    	inflater.inflate(R.menu.menu_back, menu);
    }
    
    @Override
    public void onPrepareOptionsMenu(Menu menu)
    {
    	Boolean signMode = ((LogEntryListCursorAdapter) getListAdapter()).multiSelect;
    	
    	menu.findItem(R.id.menu_add).setVisible(!signMode);
    	menu.findItem(R.id.menu_copy).setVisible(!signMode);
    	menu.findItem(R.id.menu_goto).setVisible(!signMode);
    	menu.findItem(R.id.menu_back).setVisible(signMode);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId())
        {
        case R.id.menu_add:
        	addLogEntry();
            return true;
            
        case R.id.menu_copy:
        	addNewFromPrevious();
            return true;
            
        case R.id.menu_sign:
        	signEntries();
            return true;
            
        case R.id.menu_goto:
        	goToEntry();
            return true;
            
        case R.id.menu_back:
        	toggleSignMode();
            return true;
            
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    private void addLogEntry()
    {
    	mListener.onLogEntryEditRequest(new Bundle());
    }
    
    private void addNewFromPrevious()
    {
		Bundle args = new Bundle();
		args.putBoolean(Constants.EXTRA_LOG_ENTRY_COPY, true);

		mListener.onLogEntryEditRequest(args);
    }
    
    private void signEntries()
    {
		if (!((LogEntryListCursorAdapter) getListAdapter()).multiSelect)
		{
			toggleSignMode();
		}
		else
		{
	    	// get selected ids
	    	ArrayList<Integer> logEntryIds = ((LogEntryListCursorAdapter)getListAdapter()).getSelection();
	    	
	    	// start signature activity
	    	Intent intent =  new Intent(getActivity(), SignatureActivity.class);
			intent.putExtra(Constants.EXTRA_SELECTED_LOG_ENTRY_IDS, logEntryIds);
			startActivityForResult(intent, 0);
		}
    }
    
    private void goToEntry()
    {
		// init dialog
		NumberDialog dialog = new NumberDialog(
				new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Dialog),
				R.string.log_entry_list_goto_title,
				1,
				goToSetListener);
		// show dialog
		dialog.show();
    }
}